package com.rpa.server.servicerpaserver.util;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @className: WebDriverUtil
 * @author: lzt
 * @date: 2025/1/24 10:49
 * @Version: 1.0
 * @description:
 */

public class WebDriverUtil {
    public static void setupWebDriver(ChromeOptions options) {
        WebDriverManager.chromedriver().setup();
        options.addArguments("--headless");
        options.addArguments("--disable-gpu");
        options.addArguments("--remote-allow-origins=*");

        // 最大化窗口
        options.addArguments("--start-maximized");
    }
    public static List<Map> getWebDriverDate(ChromeDriver chromeDriver) {
        WebDriverWait wait = new WebDriverWait(chromeDriver, Duration.ofSeconds(5) );
        wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.tagName("pre")));
        WebElement preElement = chromeDriver.findElement(By.tagName("pre"));
        String pageSource = preElement.getText();
        JSONObject jsonObject = new JSONObject(pageSource);
        JSONArray data = jsonObject.getJSONArray("data");
        List<Map> list = JSONUtil.toList(data, Map.class);
        return list;
    }

    public static List<Map> getWebDriverDateForName(ChromeDriver chromeDriver, String name) {
        WebDriverWait wait = new WebDriverWait(chromeDriver, Duration.ofSeconds(5) );
        wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.tagName("pre")));
        WebElement preElement = chromeDriver.findElement(By.tagName("pre"));
        String pageSource = preElement.getText();
        JSONObject jsonObject = new JSONObject(pageSource);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray jsonArray = data.getJSONArray(name);
        List<Map> list = JSONUtil.toList(jsonArray, Map.class);
        return list;
    }

    public static void closeWebDriver(ChromeDriver chromeDriver) {
        if (chromeDriver != null) {
            chromeDriver.quit();
        }
    }

}
